package departure;

import dbhandler.*;
import evthandler.EventMessage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

/**
 *
 * @author Casper, Dennis, Jackie, Jakob
 * @version 0.90
 */
public class CheckOut {

    private String outDay;
    private String today;
    private Booking booking;
    private ArrayList<Relative> relatives;

    /**
     *
     * @param booking
     */
    public CheckOut(Booking booking) {
        this.booking = booking;
        relatives = new Relative().getRelatives(booking.getGuest());
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        today = dateFormat.format(cal.getTime());
        outDay = booking.getOutDate();
        checkOut();
    }

    /**
     * Method for checking if today is the day for planned checkOut.
     * @param String OrderdDate represents the day which the guest planned to check out
     * @return Returns true if the days match
     */
    private boolean validDate() {
        boolean valid = false;
        if (today.equalsIgnoreCase(outDay)) {
            valid = true;
        } else {
            boolean respons = new EventMessage("Mismatch Betweeen Dates", "Apparently today is not the right day for checkout on the room,\nAre you sure you want to check the guest out from this room?").showConfirm();
            if (respons) {
                valid = true;
            }
        }
        return valid;
    }

    /**
     * If validDate returns true checkout procedure is launched. Else no changes are made to the booking
     */
    private final void checkOut() {
        if (!validDate()) {
            new EventMessage("No changes", "No changes were made").showMessage();
        } else {
            for (int i = 0; i < relatives.size(); i++) {
                checkProcedure(relatives.get(i).getRelative());
            }
            checkProcedure(booking.getGuest());
            booking.delete();
            new EventMessage("Guest checked out", "The guest was successfully checked out.").showMessage();
            String payment = new PayMethodDialog(null, true).returnPayment();
            Bill b = new Bill(booking, payment);
            new InvoiceForm(null, true).start(b);
        }
    }

    /**
     * If the relative guest is a businessGuest the last room number is saved !
     */
    private void checkProcedure(Guest relative) {
        if (relative.isBusinessGuest()) {
            relative.setLastRoom(booking.getRoom());
        }
    }
}
